package yaty.lee.ssh2.dao.impl;

import java.sql.SQLException;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import yaty.lee.ssh2.bean.Admin;
import yaty.lee.ssh2.dao.AdminDao;
import yaty.lee.ssh2.exception.ModelException;
import yaty.lee.ssh2.util.PageList;

public class AdminDaoImpl extends HibernateDaoSupport implements AdminDao {

	@Override
	@SuppressWarnings("unchecked")
	public PageList<Admin> list(final Admin admin, final int skip,
			final int size) throws ModelException {
		try {
			PageList<Admin> list = getHibernateTemplate().execute(
					new HibernateCallback<PageList<Admin>>() {

						@Override
						public PageList<Admin> doInHibernate(Session session)
								throws HibernateException, SQLException {
							Criteria query = session
									.createCriteria(Admin.class);
							if (admin.getAdminname() != null) {
								query.add(Restrictions.like("adminname",
										admin.getAdminname(),
										MatchMode.ANYWHERE));
							}
							query.setProjection(Projections.rowCount());
							Long count = (Long) query.uniqueResult();
							query.setProjection(null);
							query.addOrder(Order.asc("id"));
							query.setFirstResult(skip);
							query.setMaxResults(size);

							PageList<Admin> list = new PageList<Admin>(count
									.intValue());
							list.addAll(query.list());
							return list;
						}
					});
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			throw new ModelException(1, e.getMessage());
		}
	}

	@Override
	public Admin saveAdmin(Admin admin) throws ModelException {
		return null;
	}

	@Override
	public Admin load(int id) throws ModelException {
		try {
			return getHibernateTemplate().get(Admin.class, id);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ModelException(1, e.getMessage());
		}
	}

	@Override
	public void modify(Admin admin) throws ModelException {
		try {
			Admin adm = load(admin.getId());
			adm.setAdminname(admin.getAdminname());
			adm.setPassword(admin.getPassword());
			getHibernateTemplate().saveOrUpdate(adm);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ModelException(1, e.getMessage());
		}
	}

}
